﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using LuckyLoot.ServiceFacade.Implementation;
using LuckyLoot.ServiceFacade.Contracts;
using LuckyLoot.Presentation.BasePage;
using LuckyLoot.Domain.Entities;
using LuckyLoot.Common.Validation;

namespace LuckyLoot.Presentation
{
    public partial class ToolPage : LuckyLootPage
    {
        private const string QueryStringToolID = "ToolID";

        public int ToolID
        {
            set
            {
                this.ViewState[QueryStringToolID] = value;
            }
            get 
            { 
                int viewStateTypedToolID;

                if (this.ViewState[QueryStringToolID] != null)
                {
                    if (Int32.TryParse(this.ViewState[QueryStringToolID].ToString(), out viewStateTypedToolID))
                        return viewStateTypedToolID;
                }

                return 0;
            }
        }

        public bool HasSelectedRecord
        {
            get
            {
                return ToolID > 0;
            }
        }

        private void SetCommandsVisibility()
        {
            this.SterilizeTool.Visible = this.HasSelectedRecord;
        }

        private void SelectRecord(string id)
        {
            if (!string.IsNullOrWhiteSpace(id))
            {
                int intID;
                if (Int32.TryParse(id, out intID))
                    SelectRecord(intID);
            }

        }

        private void SelectRecord(int id)
        {
            ValidState.Requires<ArgumentException>(id > 0);
            var tool = this.ToolService.GetTool(id);

            SelectRecord(tool);
        }

        private void SelectRecord(LuckyLoot.Domain.Entities.Tool tool)
        {
            this.toolName.Text = tool.Name;
            this.toolDescription.Text = tool.Description;
            this.toolLastSterilization.Text = tool.LastSterilization.HasValue ? tool.LastSterilization.Value.ToString() : string.Empty;

            ToolID = tool.Id;
        }

        private void ClearRecordSelection()
        {
            this.ToolID = 0;
            this.ClearFields();
        }

        private void ClearFields()
        {
            this.toolName.Text = string.Empty;
            this.toolDescription.Text = string.Empty;
            this.toolLastSterilization.Text = string.Empty;
        }


        private IToolManagementService _toolService;
        public IToolManagementService ToolService 
        {
            get
            {
                if (_toolService == null)
                    _toolService = new ToolManagementService();

                return _toolService;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!Page.IsPostBack)
                {
                    var toolIDString = HttpContext.Current.Request.QueryString[QueryStringToolID];
                    this.SelectRecord(toolIDString);
                }

                this.SaveTool.Click += new EventHandler(SaveToolClick);
                this.SterilizeTool.Click += new EventHandler(SterilizeToolClick);
                this.SetCommandsVisibility();
                this.BindGrid();
            }
            catch (Exception ex)
            {
                MasterPage.ShowErrorMessage(ex.Message);
            }
        }

        public void SterilizeToolClick(object sender, EventArgs e)
        {
            if (HasSelectedRecord)
            {
                var tool = this.ToolService.SterilizeTool(ToolID);

                MasterPage.ShowSuccessMessage(
                    string.Format("Ferramenta \"{1}\" esterilizada com sucesso!{0}{0} Data da última esterilização: {2}.{0} Data da próxima esterilização: {3}.", 
                    Environment.NewLine, 
                    tool.Name, 
                    tool.LastSterilization.Value.Date.ToString(), 
                    tool.LastSterilization.Value.AddDays(30).Date.ToString()));

                this.BindGrid();
            }
        }

        public void SaveToolClick(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(toolName.Text))
                throw new ArgumentNullException("toolName", "É obrigatório informar o nome da ferramenta.");

            DateTime? lastSterilization = null;
            if(!string.IsNullOrWhiteSpace(toolLastSterilization.Text))
            {
                DateTime parsedDate;
                if (DateTime.TryParse(toolLastSterilization.Text, out parsedDate))
                    lastSterilization = parsedDate;
            }

            Tool tool;
            if(HasSelectedRecord)
                tool = this.ToolService.UpdateTool(ToolID, toolName.Text, toolDescription.Text, lastSterilization);
            else
                tool = this.ToolService.CreateTool(toolName.Text, toolDescription.Text, lastSterilization);

            this.SelectRecord(tool);
            this.SetCommandsVisibility();
            MasterPage.ShowSuccessMessage("Ferramenta salva com sucesso!");
            this.BindGrid();
            
        }

        private void BindGrid()
        {
            var tools = this.ToolService.GetAllTools();

            if (tools.Count() > 0)
            {
                this.toolsGrid.DataSource = tools;
                this.toolsGrid.DataBind();
                this.toolsGrid.Visible = true;
                this.toolsLabel.Visible = true;
            }
        }
    }
}